package com.insightg3.android;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class KeywordRegisterActivity extends Activity {

	private EditText txtKeyFrom;
    private EditText txtKeyTo;
    private Spinner langFrom;
    private Spinner langTo;
    private List<Map> registedKeyList;
    private String keyfile = "keyword_map.xml";

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.register_keyword);

        Spinner spinner = (Spinner)findViewById(R.id.cmdKeywordFrom);

        ArrayAdapter adapter = ArrayAdapter.createFromResource(
                this, R.array.value_where, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        Spinner spinner2 = (Spinner)findViewById(R.id.cmdKeywordTo);

        ArrayAdapter adapter2 = ArrayAdapter.createFromResource(
                this, R.array.value_where, android.R.layout.simple_spinner_item);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(adapter);

        txtKeyFrom = (EditText)findViewById(R.id.txtKeywordFrom);
        txtKeyTo = (EditText)findViewById(R.id.txtKeywordTo);
        langFrom = (Spinner)findViewById(R.id.cmdKeywordFrom);
        langTo = (Spinner)findViewById(R.id.cmdKeywordTo);

        ((Button) findViewById(R.id.btnKeywordTranslate)).setOnClickListener(mTranslateListener);
        ((Button) findViewById(R.id.btnKeywordRegister)).setOnClickListener(mKeyRegisterListener);
        ((Button) findViewById(R.id.btnKeywordInputClear)).setOnClickListener(mClearListener);
            
        //read xml file
        registedKeyList = this.readFile(keyfile);
           
        }

     

        OnClickListener mTranslateListener = new OnClickListener() {

            public void onClick(View v) {
            String languageFrom = (langFrom.getSelectedItem()).toString();
            String languageTo = ((langTo).getSelectedItem()).toString();
            String strTranslated = AndroidUtils.translateString(txtKeyFrom.getText().toString(),
                    AndroidUtils.getTranslateLanguage(languageFrom),
                    AndroidUtils.getTranslateLanguage(languageTo));
            txtKeyTo.setText(strTranslated);
            }

        };

     

        OnClickListener mKeyRegisterListener = new OnClickListener() {
            public void onClick(View v) {
            	Map keyMap = new HashMap();
                String languageFrom = (langFrom.getSelectedItem()).toString();
                String languageTo = ((langTo).getSelectedItem()).toString();
            	keyMap.put(languageFrom, txtKeyFrom.getText().toString());
            	keyMap.put(languageTo, txtKeyTo.getText().toString());
				registedKeyList.add(keyMap);
				
				writeFile(keyfile, registedKeyList);
            }
        };

     

        OnClickListener mClearListener = new OnClickListener() {
            public void onClick(View v) {
		        txtKeyFrom.setText("");
		        txtKeyTo.setText("");
            }

        };
        
    public boolean writeFile(String filepath, List<Map> keylist){
       try
       {
	       Log.d("output xml path and txt :", filepath+";");
	       OutputStream os = openFileOutput(filepath, MODE_PRIVATE);
	       OutputStreamWriter osw=new OutputStreamWriter(os);
	       String txt = outputKeylistToXML(keylist);
	       osw.write(txt);
	       osw.close();
	       os.close();
       }
       catch(FileNotFoundException e)
       {
	       return false;
       }
       catch(IOException e)
       {
	       return false;
       }
       return true;
       }
    
    public List<Map> readFile(String filepath){
    	List<Map> rtnList  = new ArrayList<Map>();
    	
    	XmlPullParser parser = Xml.newPullParser();
    	try {
			FileInputStream inputStream=openFileInput(filepath);
			
			parser.setInput(inputStream, "UTF-8");
			boolean blnItemStart = false;
			Map keyMap = new HashMap();
			    
			// XML文章の終わりまでループして解析すや1�7
			for (int eventType = parser.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = parser
					.next()) {

				String tagName;
				String tagText;
				switch (eventType) {
				// TAGの始まり
				case XmlPullParser.START_TAG:
					// TAGの名前を取得する
					tagName = parser.getName();
					if (tagName.equals("key")) {
						blnItemStart = true;
					}
					else
					// TAGの名前がjapan
					if (tagName.equals("Japan")) {
						// 次の要素へ
						parser.next();
						// 要素がTEXTだったら内容を取り出い
						if (parser.getEventType() == XmlPullParser.TEXT) {
							tagText = parser.getText();
							keyMap.put("Japan", tagText);
						}
					}
					else if (tagName.equals("China")) {
						// 次の要素へ
						parser.next();
						// 要素がTEXTだったら内容を取り出い1�7
						if (parser.getEventType() == XmlPullParser.TEXT) {
							tagText = parser.getText();
							keyMap.put("China", tagText);
						}
					}
					break;
				// TAGのおわり
				case XmlPullParser.END_TAG:
					// TAGの名前を取得する
					tagName = parser.getName();
					if (tagName.equals("key") && blnItemStart) {
						rtnList.add(keyMap);
						keyMap = new HashMap();
						blnItemStart = false;
					}
					break;
				}
			}
			Log.d("paser registed KeyList xml", rtnList.toString());
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
    	} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			Log.d("file not found", "file is not found");
		}catch (IOException e) {
				e.printStackTrace();
		}
		return rtnList;
    }

    public String outputKeylistToXML(List<Map> keylist){

        String strRtnXML = "";
        XmlSerializer serializer = Xml.newSerializer();
        StringWriter writer = new StringWriter();

        try{
            serializer.setOutput(writer);

            // <?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>
            serializer.startDocument("UTF-8",true);

            // <translation_key number=”1″>
            serializer.startTag("","translation_key");
            //serializer.attribute("","number",String.valueOf(1));

            for(Map keyMap : keylist){
                //<key data="2009-09-23″>
                serializer.startTag("","key");
                //serializer.attribute("","date","2009-09-23″);

                // <japan>xxx</japan>
                serializer.startTag("","Japan");
                serializer.text(keyMap.get("Japan").toString());
                serializer.endTag("","Japan");

                // <china>xxxx</china>
                serializer.startTag("","China");
                serializer.text(keyMap.get("China").toString());
                serializer.endTag("","China");

                //</key>
                serializer.endTag("","key");
            }
            // </translation_key>
            serializer.endTag("","translation_key");
            serializer.endDocument();
            strRtnXML = writer.toString();
        }
        catch(Exception e)
        {
            throw new RuntimeException(e);
        }
        return strRtnXML;
     }

}
